package com.sakura.mybatis.version4.listener;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.sakura.mybatis.version3.utils.SqlSessionUtils;
import com.sakura.mybatis.version4.enums.DEPT_TYPE;
import com.sakura.mybatis.version4.excel.dto.SysAgentDTO;
import com.sakura.mybatis.version4.mapper.SysAgentMapper;
import com.sakura.mybatis.version4.pojo.SysAgent;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Sakura
 * @Date 2023/12/21 10:06
 * @Version 1.0
 */
public class SysAgentDTOListener extends AnalysisEventListener<SysAgentDTO> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 500;

    private static int count = 0;

    final String pathName = "config/mybatis/version4/mybatis-config.xml";
    final String pwd="21218cca77804d2ba1922c33e0151105";//6个8

    /**
     * 缓存的数据
     */
    private List<SysAgentDTO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private List<String> existList=new ArrayList<>();

    @Override
    public void invoke(SysAgentDTO sysAgentDTO, AnalysisContext analysisContext) {

        cachedDataList.add(sysAgentDTO);

        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //数据读取完毕保存逻辑
        saveData();
    }

    private void saveData() {
        SqlSession sqlSession = null;
        try {
            sqlSession = SqlSessionUtils.getSqlSession(pathName, false);
            SysAgentMapper mapper = sqlSession.getMapper(SysAgentMapper.class);
            List<SysAgent> collect = cachedDataList.stream().map(m -> {
                SysAgent sysAgent = new SysAgent();
                sysAgent.setAgentIdNo(m.getAgentIdNo());
                sysAgent.setAgentIdType(1);//默认身份证
                sysAgent.setAgentCode(m.getAgentCode());
                sysAgent.setAgentMobile(m.getAgentMobile());
                sysAgent.setAgentName(m.getAgentName());
                sysAgent.setAgentOrgCode(m.getDeptCode().substring(0, 2));
                sysAgent.setAgentOrgName(DEPT_TYPE.getCompanyOrganization(sysAgent.getAgentOrgCode()));

                //初始化信息
                sysAgent.setAgentPwd(pwd);
                sysAgent.setAgentType(3);
                sysAgent.setAgentStatus(1);
                sysAgent.setMobileAuth("1");
                sysAgent.setEmailAuth("0");
                sysAgent.setIdAuth("1");
                sysAgent.setIdCardAuth("1");
                sysAgent.setEntryTime(new Date());
                sysAgent.setModifiedDate(new Date());
                sysAgent.setCreatedDate(new Date());
                sysAgent.setCreatedUser(DateUtil.today());
                sysAgent.setModifiedUser(DateUtil.today());
                sysAgent.setAgentLevel("2");
                sysAgent.setIsDelete(0);
                return sysAgent;
            }).collect(Collectors.toList());
            mapper.insertBatch(collect);
            sqlSession.commit();
            sqlSession.clearCache();
            //统计数据量
            count += cachedDataList.size();
            System.out.println(String.format("【%s】期数据已处理【%s】条数据!", DateUtil.today(), count));
        } catch (Exception e) {
            count -= cachedDataList.size();
            if (null != sqlSession) {
                sqlSession.rollback();
            }
            System.out.println(String.format("【%s】期数据导入失败!异常原因:%s", DateUtil.today(), e.getMessage()));
        } finally {
            if (null != sqlSession) {
                sqlSession.close();
            }
        }
    }
}
